﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Acme.BookStore.RBACServices
{
    /// <summary>
    /// 管理和清理验证码
    /// </summary>
    public class CaptchaCleanupService: BackgroundService
    {
        private readonly ILogger<CaptchaCleanupService> _logger;
        private readonly IHostEnvironment _environment;
        private readonly TimeSpan _interval = TimeSpan.FromMinutes(3);

        public CaptchaCleanupService(ILogger<CaptchaCleanupService> logger, IHostEnvironment environment)
        {
            _logger = logger;
            _environment = environment;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    CleanUpCaptchaFolder();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error occurred while cleaning up captcha folder.");
                }

                await Task.Delay(_interval, stoppingToken);
            }
        }

        private void CleanUpCaptchaFolder()
        {
            var captchaFolderPath = Path.Combine(_environment.ContentRootPath, "wwwroot", "captcha");
            if (Directory.Exists(captchaFolderPath))
            {
                var files = Directory.GetFiles(captchaFolderPath);
                foreach (var file in files)
                {
                    File.Delete(file);
                }
                _logger.LogInformation("Captcha folder cleaned up successfully.");
            }
        }
    }
}
